using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Hsp.WebNovels.Common.Constants;
using Hsp.WebNovels.Common.Utility;
using Hsp.WebNovels.Model;
using Hsp.WebNovels.Model.Data;
using Hsp.WebNovels.Model.Dtos;
using Hsp.WebNovels.Model.Models;
using Hsp.WebNovels.Model.Extensions;
using Hsp.WebNovels.Web.Utility;
using System.Web;
using Hsp.WebNovels.Web.Models;
using Hsp.WebNovels.IService;

namespace Hsp.WebNovels.Web.Areas.Replaces.Controllers
{
    /// <summary>
    /// 内容替换控制器
    /// </summary>
    [Area("Replaces")]
    public class Controller : AreaBaseController
    {
        #region 控制器初始化
        
        private readonly IMapper _mapper;
        private readonly ILogger<Controller> _logger;
        private readonly NovelsContext _context;
        
        /// <summary>
        /// 内容替换控制器构造函数
        /// </summary>
        public Controller(ILogger<Controller> logger, NovelsContext context, IMapper mapper) : base(logger, context, mapper)
        {
            this._logger = logger;
            this._mapper = mapper;
            this._context = context;
        }
        
        #endregion
        
        // GET: Replaces/
        public async Task<IActionResult> Index()
        {
            return _context.Replaces != null ? 
                          View(await _context.Replaces.Skip(0).Take(50).ToListAsync()) :
                          Problem("Entity set 'WisdomRecyclingContext.Replaces' is null.");
        }
        
        // POST: Replaces//Delete/5
        [HttpPost, ActionName("Delete")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();
            
            try
            {
            if (_context.Replaces == null)
            {
                return Problem("Entity set 'WisdomRecyclingContext.RecyclingSites' is null.");
            }
            var Replace = await _context.Replaces.FindAsync(id);
            if (Replace != null)
            {
                _context.Replaces.Remove(Replace);
            }
            
            await _context.SaveChangesAsync();
            await transaction.CommitAsync(); // 事务提交
            return Json(new { success = true, message = "内容替换删除成功" });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(); // 事务回滚
                _logger.LogError($"{nameof(DeleteConfirmed)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }
        
        /// <summary>
        /// 批量删除数据
        /// POST: Replaces//BatchDelete/5,7
        /// </summary>
        /// <param name="id">数据编号集合</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDelete(string? id)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();
            
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return Json(new { success = false, Message = "要删除的内容替换数据主键集合为空！" });
                }
                var idarr = id.Trim().Split(',');
                foreach (var idd in idarr)
                {
                    var Replace = await _context.Replaces.FindAsync(int.Parse(idd));
                    if (Replace != null) _context.Replaces.Remove(Replace);
                }
                await _context.SaveChangesAsync();
                await transaction.CommitAsync(); // 事务提交
                return Json(new { success = true, message = "内容替换数据删除成功！" });
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync(); // 事务回滚
                _logger.LogError($"{nameof(BatchDelete)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        private bool ReplaceExists(int id)
        {
            return _context.Replaces.Any(e => e.Id == id);
        }


        #region 内容替换列表数据视图

        /// <summary>
        /// 内容替换列表数据视图
        /// GET: Replaces//TableList
        /// </summary>
        /// <param name="mid">菜单ID</param>
        /// <param name="mapname">菜单路径</param>
        /// <returns></returns>
        public IActionResult TableList(int? mid, string? mapname)
        {
            ReplaceDto dto = new();
            var model = _mapper.Map<ReplaceViewModel>(dto);
            return View(model);
        }

        #endregion 

        #region 内容替换分页数据查询

        /// <summary>
        /// 内容替换分页数据查询
        /// GET: Replaces//PageList
        /// </summary>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="title">检索关键词</param>
        /// <returns></returns>
        public JsonResult PageList(int? pageNumber, int? pageSize, string? title)
        {
            try
            {
                #region 参数处理
                
                var urlDecode = HttpUtility.UrlDecode(title);
                if (urlDecode != null) title = title == null ? "" : urlDecode.Trim();

                string strQry = "";

                if (!string.IsNullOrEmpty(title))
                {
                    strQry += string.Format(@" AND (r.Title LIKE '%{0}%' OR r.ABCDEF LIKE '%{0}%')", title);
                }
                
                #endregion

                #region 分页及页码数据处理处理

                if (!pageNumber.HasValue) pageNumber = 1;
                if (!pageSize.HasValue) pageSize = 10;

                var skip = (pageNumber.Value - 1) * pageSize.Value;

                var min = (pageNumber - 1) * pageSize + 1;
                var max = pageNumber * pageSize;

                #endregion

                var strSql = string.Format(@"
	                ;WITH PageTb AS (
		                SELECT ROW_NUMBER() OVER (ORDER BY CreateTime) RowNumber
			                , Id,NovelId,Source,Target,Priority,Deleted,CreateTime,UpdateTime
		                FROM dbo.[Replaces] r WHERE (1 = 1) 
		                 {2} 
		                )
	                SELECT * 
	                FROM PageTb a
	                CROSS JOIN (SELECT MAX(RowNumber) AS RecordCount FROM PageTb) AS b 
	                WHERE (a.RowNumber BETWEEN {0} AND {1});
                 ", min, max, strQry);

                var list = _context.Database.SqlQuery<ReplaceDto>(strSql)?.ToList();

                return Json(new { success = true, total = list?.Count > 0 ? list[0].RecordCount : 0, rows = list });
            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(PageList)}：{ex}");
                return Json(new { success = false, total = 0, rows = new List<Hashtable>(), message = ex.Message });
            }
        }

        #endregion

        #region 内容替换数据保存

        /// <summary>
        /// 内容替换数据保存
        /// POST: Replaces//Save
        /// </summary>
        /// <param name="Replace">内容替换</param>
        /// <returns></returns>
        public async Task<IActionResult> Save([FromBody] Replace Replace)
        {
            try
            {
                string flag;
                if (!ReplaceExists(Replace.Id) || Replace.Id == 0)
                {
                    flag = "添加";
                    Replace.CreatorId = base.CurrentUser?.Id;
                    Replace.CreateTime = DateTime.Now;
                    _context.Add(Replace);
                }
                else
                {
                    flag = "修改";
                    Replace.ModifierId = base.CurrentUser?.Id;
                    _context.Update(Replace);
                }

                await _context.SaveChangesAsync();

                return Json(new { success = true, message = $"内容替换数据{flag}成功!" });

            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(Save)}：{ex}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        #endregion

    }
}
